

import java.awt.EventQueue;

import javax.swing.JFrame;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;

public class ClientGUI extends JFrame implements ActionListener {
	static JButton b;
	static TextArea t1;
	static TextField t2;
	static TextField t3;
	static Panel p1 = new Panel();
	static Panel p2 = new Panel();
	static Panel p3 = new Panel();
	static JLabel l1, l2;
	static int port;
	static Socket c_socket;
	static InputStream in_data;
	static OutputStream out_data;
	static String str;
	static String str2;
	static int i = 0;

	ClientGUI() {
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		add(p1, BorderLayout.NORTH);
		add(p2, BorderLayout.CENTER);
		add(p3, BorderLayout.SOUTH);

		l1 = new JLabel("聊天信息");

		p1.add(l1);

		t1 = new TextArea(25, 60);
		p2.add(t1);
		
		
		t3 = new TextField(10);
		t3.setText("newuser");
		p3.add(t3);
		
		l2 = new JLabel("说：");
		p3.add(l2);
		t2 = new TextField(32);
		t2.addKeyListener(new KeyListener() {
			
			
			
			@Override
			public void keyPressed(KeyEvent ke) {
				if(ke.getKeyCode()==ke.VK_ENTER){
					actionPerformed(null);
				}
			}

			@Override
			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}
		});
		p3.add(t2);

		b = new JButton("发送");
		b.addActionListener(this);
		b.setEnabled(false);
		p3.add(b);
		
		setSize(480, 500);
		setVisible(true);

		try {
			c_socket = new Socket("localhost", 9901);
			b.setEnabled(true);
			in_data = c_socket.getInputStream();
			out_data = c_socket.getOutputStream();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(in_data,"utf-8"));
			String msg = null;
			while((msg = br.readLine()) != null){
				t1.append(msg+"\n");
			}
		} catch (IOException e) {
			System.out.println("接收消息出错"+e.getMessage());
			t1.append("接收消息出错！");
		}
	}
	
	

	public void actionPerformed(ActionEvent eee) {
		try {
			str2 = t2.getText();
			if(str2.length()==0)return;
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out_data,"utf-8"));
			bw.write(t3.getText() +": "+str2);
			bw.newLine();
			bw.flush();
			t2.setText("");
			t1.append(str2 + "\n");
		} catch (IOException e) {
			System.out.println("发送错误" + e.getMessage());
		}
	}

	public static void main(String args[]) throws Exception {
		new ClientGUI();
	}

}
